package com.tianji.remark.task;

import com.tianji.common.utils.CollUtils;
import com.tianji.remark.constant.RedisConstants;
import com.tianji.remark.domain.dto.BizIdAndTypeDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.mapper.LikedStatMapper;
import com.tianji.remark.service.ILikedRecordService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author Xinxuan Zhuo
 * @version 2024/3/6
 * <p>
 * xxl-job 持久化redis的点赞数据到数据库，查询时从数据库中加载预热
 * </p>
 */
@SuppressWarnings("ALL")
@Slf4j
@Component
public class LikesRecordPersistenceDBJob {


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private LikedRecordMapper likedRecordMapper;

    @Resource
    private LikedStatMapper statMapper;

    private final static String KEY;

    static {
        KEY = RedisConstants.LIKE_BIZ_KEY_PREFIX;
    }


    @XxlJob("persistenceDBHandler")
    public void persistenceDBHandler() {
        try{
            log.info("=====持久化redis的点赞数据到数据库任务执行了=====");
            // 获取bizId
            List<BizIdAndTypeDTO> bizIdAndTypeDTOS = statMapper.queryAllBizIdAndType();
            if (CollUtils.isEmpty(bizIdAndTypeDTOS)) {
                return;
            }
            // 获取redis中的所有数据 ->connection.sMembers(rawKey);
            List<Object> objects = stringRedisTemplate.executePipelined((RedisCallback<Object>) connection -> {
                StringRedisConnection src = (StringRedisConnection) connection;
                // 获取点赞的userId
                for (BizIdAndTypeDTO data : bizIdAndTypeDTOS) {
                    String key = KEY + data.getBizId();
                    src.sMembers(key);
                }
                return null;
            });
            // 持久化到数据库，更新或者新增
            LinkedHashSet<String> userIdSet = (LinkedHashSet<String>)objects.get(0);
            Iterator<String> iterator = userIdSet.iterator();
            List<LikedRecord> records = new LinkedList<>();
            for (int i = 0; i < bizIdAndTypeDTOS.size(); i++) {
                for (Integer j = 0; j < bizIdAndTypeDTOS.get(i).getLikeTimes(); j++) {
                    LikedRecord record = new LikedRecord();
                    record.setBizId(bizIdAndTypeDTOS.get(i).getBizId());
                    record.setBizType(bizIdAndTypeDTOS.get(i).getBizType());
                    if (iterator.hasNext()){
                        record.setUserId(Long.parseLong(iterator.next()));
                    }
                    records.add(record);
                }
            }
            likedRecordMapper.saveOrUpdateBatch(records);
            log.info("=====持久化redis的点赞数据到数据库任务结束了=====");
        }catch (Exception e){
            log.error("=====持久化redis的点赞数据到数据库任务出错了：{}=====",e.getMessage());
            e.printStackTrace();
        }

    }


}
